package bomber.model;

import java.util.Random;


public class GameManager {
	private GameBoxArray boxArray;
	private int size;
	private int bomb;
	private int rock;
	private int help;
	private String error;

	public GameManager(int size, int bomb, int rock, int help) {
		this.size = size;
		this.bomb = bomb;
		this.rock = rock;
		this.help = help;
		this.error = "";

		this.validManager();
		this.newGame();
	}

	private void validManager() {
		if (this.size < 2) this.error += "Size is too small.\n";
		if (this.size > 1000) this.error += "Size is too large.\n";
		if (this.rock > 9) this.error += "Rock is too more.\n";
		if (this.bomb > (this.size*this.size)) this.error += "Bomb is too more.\n";
	}

	public void newGame() {
		try {
			if (this.hasError()) {
				this.boxArray = new GameBoxArray(this.size);

				Random rand = new Random();
				int bombNum = this.bomb;
				int m = 0;
				int n = 0;

				while (bombNum > 0) {
					m = rand.nextInt(this.size);
					n = rand.nextInt(this.size);
					
					if (this.boxArray.hasBomb(m, n) == false) {
						this.boxArray.setBomb(m, n);
						bombNum--;
					}
				}

				for(int i = 0; i < this.size; i++) {
					for(int j = 0; j < this.size; j++) {
						if (this.boxArray.hasBomb(i, j) == false) {
							this.boxArray.makeInfo(i, j, this.rock);
						}
					}
				}
			}
		}
		catch (Exception ex) {
			this.error += String.format("Init new game error: %s\n",ex.toString());
		}
	}


	public boolean hasError() {
		return (this.error.length() == 0);
	}

	public GameBox getGameBox(int i, int j) {
		return this.boxArray.getOne(i, j);
	}

	public String getError() {
		return this.error;
	}

	public int getHelp() {
		return this.help;
	}

	public int getSize() {
		return this.size;
	}
}
